package com.qingcheng.timer;

import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Set;

/**
 * @Author:boy
 * @Date:2019/7/22
 * @description:
 * @ModifiedBy:
 */
@Component
public class LoadGoodsPushRedis {
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0/30 * * * * ?")
    public void loadGoodsPushRedis() {
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date dateMenu : dateMenus) {
            String extName = DateUtil.date2Str(dateMenu);
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status", "1");//审核通过
            criteria.andGreaterThan("num", 0);//库存数量大于0
            criteria.andGreaterThan("startTime", dateMenu);//大于等于开始时间
            criteria.andLessThan("endTime", DateUtil.addDateHour(dateMenu, 2));//小于结束时间
            Set keys = redisTemplate.boundHashOps("SeckillGoods_" + extName).keys();
            if (keys != null && keys.size() > 0) {//判断是否已存在
                criteria.andNotIn("id", keys);
            }
            //从数据库查询
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);
            for (SeckillGoods seckillGood : seckillGoods) {
                //存入redis缓存中
                redisTemplate.boundHashOps("SeckillGoods_" + extName).put(seckillGood.getId(), seckillGood);
                //商品库存放入redis队列中防止商品超卖 构建库存数组
                long[] ids=new long[seckillGood.getStockCount()];
                Arrays.fill(ids,seckillGood.getId());
                //保存在redis队列中
                redisTemplate.boundListOps("SeckillGoodsCountList_"+seckillGood.getId()).leftPush(ids);
                //自增计数器
                redisTemplate.boundHashOps("SeckGoodsCount").increment(seckillGood.getId(),seckillGood.getStockCount());
            }
        }
    }
}
